#include <iostream>
#include <string>
#include <unistd.h>
#include <mysql/mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "quitesix";
const std::string passwd = "xzh3272016219XZH@";
const std::string db = "conn";
unsigned int port = 8888;

int main()
{
    std::cout << mysql_get_client_info() << std::endl;
    MYSQL *mq = mysql_init(nullptr);
    if (mq == nullptr)
    {
        std::cerr << "mysql_init error" << std::endl;
        return 1;
    }
    if (!mysql_real_connect(mq, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0))
    {
        std::cerr << "mysql connect error" << std::endl;
        return 2;
    }
    std::cout << "connect sucess" << std::endl;

    std::string sql = "select * from user";
    int n = mysql_query(mq, sql.c_str());
    if (n != 0)
    {
        std::cout << sql << " error: " << n << std::endl;
        return 3;
    }
    MYSQL_RES *res = mysql_store_result(mq);
    int rows = mysql_num_rows(res);
    int columns = mysql_num_fields(res);
    std::cout << "rows: " << rows << " columns: " << columns << std::endl;

    MYSQL_FIELD *field = mysql_fetch_fields(res);
    for (int i = 0; i < columns; i++)
    {
        std::cout << field[i].name << " ";
    }
    std::cout << std::endl;

    MYSQL_ROW line;
    for (int i = 0; i < rows; i++)
    {
        line = mysql_fetch_row(res);
        for (int j = 0; j < columns; j++)
        {
            std::cout << line[j] << " ";
        }
        std::cout << std::endl;
    }

    mysql_free_result(res);

    // while (true)
    // {
    //     std::cout << "Please Enter# ";
    //     std::getline(std::cin, sql);
    //     int n = mysql_query(mq, sql.c_str());
    //     if (n == 0)
    //         std::cout << sql << " success: " << n << std::endl;
    //     else
    //     {
    //         std::cout << sql << " error: " << n << std::endl;
    //         break;
    //     }
    // }
    mysql_close(mq);

    return 0;
}